#include <iostream>
#include <csignal>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h> // 用于 exit 函数

// 打印信号是否在集合中的辅助函数
void print_membership(const sigset_t *set, int signo, const char *signame) {
    int ret = sigismember(set, signo);
    if (ret == -1) {
        perror("sigismember");
        exit(EXIT_FAILURE);
    }
    printf("%s(%d) 是否在集合中: %s\n", signame, signo, ret ? "是" : "否");
}

int main() {
    sigset_t set;
    int ret;

    // 1. 初始化空集合
    if (sigemptyset(&set) == -1) {
        perror("sigemptyset");
        exit(EXIT_FAILURE);
    }
    printf("\n初始化空集合后:\n");
    print_membership(&set, SIGINT, "SIGINT");   // 检查 SIGINT(2)
    print_membership(&set, SIGQUIT, "SIGQUIT"); // 检查 SIGQUIT(3)

    // 2. 添加 SIGINT 和 SIGQUIT 到集合
    if (sigaddset(&set, SIGINT) == -1) {
        perror("sigaddset(SIGINT)");
        exit(EXIT_FAILURE);
    }
    if (sigaddset(&set, SIGQUIT) == -1) {
        perror("sigaddset(SIGQUIT)");
        exit(EXIT_FAILURE);
    }
    printf("\n添加 SIGINT 和 SIGQUIT 后:\n");
    print_membership(&set, SIGINT, "SIGINT");
    print_membership(&set, SIGQUIT, "SIGQUIT");

    // 3. 删除 SIGQUIT
    if (sigdelset(&set, SIGQUIT) == -1) {
        perror("sigdelset(SIGQUIT)");
        exit(EXIT_FAILURE);
    }
    printf("\n删除 SIGQUIT 后:\n");
    print_membership(&set, SIGQUIT, "SIGQUIT");

    // 4. 填充所有信号
    if (sigfillset(&set) == -1) {
        perror("sigfillset");
        exit(EXIT_FAILURE);
    }
    printf("\n填充所有信号后:\n");
    print_membership(&set, SIGALRM, "SIGALRM"); // 检查 SIGALRM(14)
    print_membership(&set, SIGKILL, "SIGKILL"); // SIGKILL(9) 不可阻塞

    // 5. 尝试删除 SIGALRM
    if (sigdelset(&set, SIGALRM) == -1) {
        perror("sigdelset(SIGALRM)");
        exit(EXIT_FAILURE);
    }

    if (sigdelset(&set, SIGKILL) == -1) {
        perror("sigdelset(SIGKILL)");
        exit(EXIT_FAILURE);
    }

    printf("\n删除 SIGALRM 后:\n");
    print_membership(&set, SIGALRM, "SIGALRM");
    print_membership(&set, SIGKILL, "SIGKILL");


    return 0;
}

// int main()
// {
//     std::signal(SIGINT, [](int signal) {
//         std::cout << "SIGINT received" << std::endl;
//     });

//     std::signal(SIGTERM, [](int signal) {
//         std::cout << "SIGTERM received" << std::endl;
//     });

//     std::cout << "Waiting for signal..." << std::endl;
//     pause();
//     std::cout << "Signal received" << std::endl;

//     return 0;
// }